<?php
namespace App\Api\Fcjd;


use PhalApi\Api;
use PhalApi\Exception\BadRequestException;

// 引入鉴权类
use Qiniu\Auth;
// 引入上传类
use Qiniu\Storage\UploadManager;
// 引入七牛云存储类
use Qiniu\Storage\BucketManager;

/**
 * 七牛云上传autox
 *   @desc 七牛云上传
 */
class Qiniu extends Api
{

    public function getRules()
    {
        return array(
            'veryEasyAi' => array(),
        );
    }


    /**
     * 非常简单传七牛
     * @desc 七牛token
     * @return array data 签名url
     * @exception 测试服
     */
    public function veryEasyAi()
    {
        // 最简单的处理方式
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *');

        $accessKey = 'KgCzxHSGM7pTsrTZbQptzoow42e5IcFOMeFrIoQz';
        $secretKey = 'xcloaEa4X3XzqXKDmz_1U1AFtNI1jlbodaHoNOQ4';
        // 初始化签权对象
        $auth = new Auth($accessKey, $secretKey);
        $bucket = 'hongkongidcard';
        // 生成上传Token
        $token = $auth->uploadToken($bucket);
        $uploadMgr = new UploadManager();
        // 构建 BucketManager 对象
        $bucketMgr = new BucketManager($auth);

        // //APP例表
        // // $task_all = \PhalApi\DI()->notorm->phone_app->where('state', 1)->fetchAll();
        //文件例表
        $filelist =  $this->AllListFiles('VeryEasyAI');
        
        foreach ($filelist as $key => $value) {
            $info = pathinfo($value);
            $filename = $info['basename'];
            $path = $info['dirname'];
            $url = "http://hongkongidcard.wenfree.cn/". $path . '/' . $filename;

            $fileInfo = \PhalApi\DI()->notorm->phone_auto_file->where(array( 'url' => $url ))->fetchOne();
            if( $fileInfo ){
                \PhalApi\DI()->notorm->phone_auto_file->where(array( 'id' => $fileInfo['id'] ))->update( array( 'md5' => md5_file($value), 'update_time' => date("Y-m-d H:i:s", time()) ) );
            }else{
                \PhalApi\DI()->notorm->phone_auto_file->insert(  
                    array(
                        "name" => $filename,
                        "path" => $path,
                        "url" => "http://hongkongidcard.wenfree.cn/". $path . '/' . $filename,
                        "md5" => md5_file($value),
                        'state' => 1,
                        "create_time" => date("Y-m-d H:i:s", time()),
                    )
                );
            }
        }

        $res = array();
        $Nochange = array();
        foreach ($filelist as $key => $value) {
            $filePath = $value;
            $key = $value;

            $localhost = \PhalApi\DI()->cache->get($filePath);
            if( strpos($filePath, '.git/') || $localhost == md5_file($filePath) ){
                //文件一致无需更新
                $Nochange[]=$value;
            }else{

                try {
                    //七牛云上传
                    $bucketMgr->delete($bucket, $key);
                    list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
                    if ($err !== null) {
                        
                    } else {
                        $curl = new \PhalApi\CUrl();
                        $url = "https://api.wenfree.cn/?s=App.Notice.Dingding&content=【脚本更新】". $value;
                        $curl->get($url, 3000);
        
                        $res[]=$ret;
                        \PhalApi\DI()->cache->set($filePath, md5_file($filePath), 24*60*60*365);
                    }
                } catch (Exception $e) {
                    // 处理异常
                    // echo "捕获到异常：",  $e->getMessage(), "\n";
                    return [$value, $e->getMessage()];
                }

                // $res[]=$value;
            }
        }


        // 在完成文件上传后，如果有更新，则标记所有设备需要更新
        if (!empty($res)) {
            $activeFiles = \PhalApi\DI()->notorm->phone_auto_file
                ->where('state', 1)
                ->fetchAll();
            
            \PhalApi\DI()->cache->set('veryeasyai', $activeFiles, 24*60*60*30);
            \PhalApi\DI()->notorm->phone_list->update(array('need_update' => 1));
        }

        return array( 'update' => $res, 'Nochange' => $Nochange);
    }
    

    private function AllListFiles($dir) {
        $files = array();

        // return is_dir($dir);

        if (is_dir($dir)) {
            // 打开目录
            if ($dh = opendir($dir)) {
                while (($file = readdir($dh)) !== false) {
                    // 跳过 '.' 和 '..'
                    if ($file != '.' && $file != '..') {
                        $filePath = $dir . '/' . $file;
                        if (is_dir($filePath)) {
                            // 如果是目录，递归调用
                            $files = array_merge($files, $this->AllListFiles($filePath));
                        } else {
                            // 如果是文件，添加到数组
                            if( strpos($filePath, '.git/') == false && strpos($filePath, '.gitignore') == false ){
                                $files[] = $filePath;
                            }
                        }
                    }
                }
                closedir($dh);
            }
        }
        return $files;
    }
}
